package com.base.cn.platform.os.controller.classes;

import com.base.cn.platform.os.common.classes.topic.ClassesTopicClassifyEnum;
import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.classes.Classes;
import com.base.cn.platform.os.entity.classes.member.ClassesMember;
import com.base.cn.platform.os.entity.course.cou.buy.CourseBuyRecord;
import com.base.cn.platform.os.service.classes.ClassesBiz;
import com.base.cn.platform.os.service.classes.member.ClassesMemberBiz;
import com.base.cn.platform.os.service.classes.topic.ClassesTopicBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 班级
 *
 * @author SK
 * @since 2018-05-08
 */
@RestController
@RequestMapping("/course")
public class ClassesController extends BaseController {

    @Autowired
    private ClassesBiz classesBiz;
    @Autowired
    private ClassesMemberBiz classesMemberBiz;
    @Autowired
    private ClassesTopicBiz classesTopicBiz;

    /**
     * 获取班级数量
     * @param classes 查询条件
     * @return BigDecimal数量
     */
    @RequestMapping("/getClassCount")
    public BigDecimal getClassCount(@RequestBody Classes classes){
        return classesBiz.getClassCount(classes);
    }

    /**
     * 查询课程下的班级
     * @param courseId 课程ID
     * @return 班级列表
     */
    @RequestMapping("/findCourseToClassesList")
    public List<Classes> findCourseToClassesList(@RequestParam("courseId") BigDecimal courseId){
        return classesBiz.find("courseId = "+courseId,5,null);
    }

    /**
     * 班级话题分类统计数量
     *
     * @param classesId 班级id
     * @return 班级话题分类统计数量
     */
    @RequestMapping("/classesTopicStatistics")
    public Map<String, Object> classesTopicStatistics(@RequestParam(value = "classesId", required = false) BigDecimal classesId,
                                                      @RequestParam(value = "userId", required = false) BigDecimal userId) {
        Map<String, Object> statistics = new HashMap<>();
        Map<Integer, Long> statisticsMap = classesTopicBiz.classesTopicStatistics(classesId, userId);
        Map<Integer, String> classifies = ClassesTopicClassifyEnum.valueMap();
        classifies.forEach((k, v) -> statistics.put(v, statisticsMap.getOrDefault(k, 0L)));
        return statistics;
    }

    /**
     * 根据id查询班级
     *
     * @param id         试卷id
     * @param setSubject 设置专业
     * @param setCreator 设置创建人
     * @param setCourse  设置课程
     * @param setMember  设置成员
     * @param order      排序 1.班主任 -> 普通学员
     * @param identity   1.普通学员 2.班级管理员 3.班主任
     */
    @RequestMapping("/findClassesById")
    public Classes findClassesById(@RequestParam("id") BigDecimal id,
                                   @RequestParam("setSubject") boolean setSubject,
                                   @RequestParam("setCreator") boolean setCreator,
                                   @RequestParam("setCourse") boolean setCourse,
                                   @RequestParam("setMember") boolean setMember,
                                   @RequestParam(value = "order", required = false) Integer order,
                                   @RequestParam("identity") int... identity) {
        return classesBiz.findClassesById(id, setSubject, setCreator, setCourse, setMember, order, identity);
    }

    /**
     * 通过ID串获取班级数据
     * @param ids ID串
     * @param setSubject 是否设置专业数据
     * @param setCreator 是否设置创建人数据
     * @return
     */
    @RequestMapping("/findClassesByIds")
    public Map<BigDecimal,Classes> findClassesByIds(@RequestParam("ids") String ids,
                                                    @RequestParam("setSubject") boolean setSubject,
                                                    @RequestParam("setCreator") boolean setCreator){
        return  classesBiz.findClassesByIds(ids,setSubject,setCreator);
    }

    /**
     * 查询班级列表
     *
     * @param classes     班级查询条件
     * @param currentPage 当前页
     * @param pageSize    每页数据条数
     * @param setSubject  设置专业
     * @param setCreator  设置创建人
     * @param setCourse   设置课程
     * @param setMember   设置成员
     * @param identity    1.普通学员 2.班级管理员 3.班主任
     * @return 班级列表
     */
    @RequestMapping("/findClassesListPage")
    public PageInfo<Classes> findClassesListPage(@RequestBody Classes classes,
                                                 @RequestParam("currentPage") int currentPage,
                                                 @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                                 @RequestParam("setSubject") boolean setSubject,
                                                 @RequestParam("setCreator") boolean setCreator,
                                                 @RequestParam("setCourse") boolean setCourse,
                                                 @RequestParam("setMember") boolean setMember,
                                                 @RequestParam("identity") int... identity) {
        Pagination pagination = new Pagination();
        if (DataUtil.isPositive(pageSize)) {
            pagination.setPageSize(pageSize);
        }
        pagination.setCurrentPage(currentPage);
        return classesBiz.findClassesListPage(classes, pagination, setSubject, setCreator, setCourse, setMember, identity);
    }


    /**
     * 查询个人班级列表
     *
     * @param cusUserId   前台用户id
     * @param currentPage 当前页
     * @param pageSize    每页数据条数
     * @return 班级列表
     */
    @RequestMapping("/findClassesPersonalListPage")
    public PageInfo<Classes> findClassesPersonalListPage(@RequestParam("cusUserId") BigDecimal cusUserId,
                                                           @RequestParam(value = "currentPage", required = false, defaultValue = "1") int currentPage,
                                                           @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        ClassesMember classesMember = new ClassesMember();
        classesMember.setMemberId(cusUserId);
        classesMember.setIdentity(1);
        classesMember.setStatus(1);
        return classesMemberBiz.findClassesPersonalListPage(page,classesMember);
    }

    /**
     * 查询个人班级列表
     *
     * @param cusUserId   前台用户id
     * @return 班级列表
     */
    @RequestMapping("/findClassesPersonalList")
    public List<Classes> findClassesPersonalList(@RequestParam("cusUserId") BigDecimal cusUserId) {
        ClassesMember classesMember = new ClassesMember();
        classesMember.setMemberId(cusUserId);
        classesMember.setIdentity(1);
        classesMember.setStatus(1);
        return classesMemberBiz.findClassesPersonalList(classesMember);
    }

    /**
     * 购课未加入集合的子集起点
     *
     * @param tc  {@link PageInfo#getTotal()}
     * @param end {@code currentPage * pageSize}
     * @param ps  {@link Pagination#pageSize}
     * @return 子集起点
     */
    private int start(long tc, int end, int ps) {
        long start = end - tc - ps;
        return start < 0 ? 0 : (int) start;
    }

    /**
     * 购课未加入集合的子集终点
     *
     * @param tc   {@link PageInfo#getTotal()}
     * @param end  {@code currentPage * pageSize}
     * @param size 购课未加入总数
     * @return 子集终点
     */
    private int end(long tc, int end, int size) {
        return end - tc >= size ? size : (int) (end - tc);
    }

    private int pageSize(Integer pageSize) {
        if (DataUtil.isPositive(pageSize)) {
            return pageSize;
        }
        return new Pagination().getPageSize();
    }

    private void resetPageInfo(PageInfo<Classes> pageInfo) {
        int pageSize = pageSize(pageInfo.getPageSize());
        long total = pageInfo.getTotal();
        long pages = total / pageSize;
        pages = total % pageSize == 0 ? pages : pages + 1;
        pageInfo.setPages((int) pages);
    }

    private List<Classes> nonJoinedClassesList(List<ClassesMember> memberList, List<CourseBuyRecord> recordList) {
        if (ObjectUtils.isEmpty(recordList)) {
            return Collections.emptyList();
        }
        Map<BigDecimal, ClassesMember> memberMap = memberList.stream().filter(e->DataUtil.idIsNotNull(e.getCourseId())).collect(Collectors.toMap(e->e.getCourseId(),e->e));
        //DataUtil.toMap(memberList, ClassesMember::getCourseId);
        List<CourseBuyRecord> filterList = recordList.stream().filter((v) -> !memberMap.containsKey(v.getCourseId())).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(filterList)) {
            return Collections.emptyList();
        }
        String courseIds = DataUtil.joining(filterList, CourseBuyRecord::getCourseId);
        Classes condition = new Classes();
        condition.setCourseIds(courseIds);
        return classesBiz.findClassesList(condition, false, false, false, false);
    }

    private PageInfo<Classes> joinedClassesList(List<ClassesMember> memberList, Pagination pagination) {
        if (ObjectUtils.isEmpty(memberList)) {
            return new PageInfo<>();
        }
        String classesIds = DataUtil.joining(memberList, ClassesMember::getClassesId);
        String where = " id in (" + classesIds + ")";
        return classesBiz.findPage(where, pagination, null);
    }

    /**
     * 保存班级
     *
     * @param classes 班级
     * @return 保存结果
     */
    @RequestMapping("/saveClasses")
    public Map<String, Object> saveClasses(@RequestBody Classes classes) {
        Map<String, Object> check = this.checkClasses(classes);
        if (check != null) {
            return check;
        }
        if(StringUtils.isEmpty(classes.getStudentLimitCount())){
            classes.setStudentLimitCount(0);
        }
        if(StringUtils.isEmpty(classes.getStudentCount())){
            classes.setStudentCount(0);
        }
        classes = classesBiz.saveClasses(classes);

        return ResultUtil.SUCCESS("保存班级成功",classes);
    }


    /**
     * 更新班级封面
     *
     * @param classes 班级
     * @return 保存结果
     */
    @RequestMapping("/saveClassesImg")
    public Map<String, Object> saveClassesImg(@RequestBody Classes classes) {

        classesBiz.updateById(classes,null);
        return ResultUtil.SUCCESS("更新班级封面成功");
    }

    /**
     * 更新班级状态
     *
     * @param ids    班级id
     * @param status 班级状态 1.正常 2.停班
     * @return 操作结果
     */
    @RequestMapping("/updateClassesStatus")
    public Map<String, Object> updateClassesStatus(@RequestParam("ids") String ids,
                                                   @RequestParam("status") int status) {
        ids = DataUtil.filterNotNumberStr(ids);
        if (StringUtils.isEmpty(ids)) {
            return ResultUtil.ERROR("请选择操作的班级");
        }
        classesBiz.updateClassesStatus(ids, status);
        return ResultUtil.SUCCESS("更新班级状态成功");
    }



    /**
     * 更新班级封面
     *
     * @param courseId 课程Id
     * @return 保存结果
     */
    @RequestMapping("/getCourseRelevanceClasses")
    List<Map> getCourseRelevanceClasses(@RequestParam(value = "courseId") BigDecimal courseId){
      return   classesBiz.getCourseRelevanceClasses(courseId);
    }



    /**
     * 更新班级简介
     *
     * @param classes 班级
     * @return
     */
    @RequestMapping("/editBrief")
    public Map<String, Object> editBrief(@RequestBody Classes classes) {

        classesBiz.updateById(classes,null);
        return ResultUtil.SUCCESS("修改成功");
    }

    /**
     * 检查保存班级数据
     *
     * @param classes 班级
     */
    private Map<String, Object> checkClasses(Classes classes) {
        if (StringUtils.lengthOutOfRange(classes.getName(), 1, 30)) {
            return ResultUtil.ERROR("班级名称1~30个字符");
        }
        if (StringUtils.isEmpty(classes.getSubjectIds())) {
            return ResultUtil.ERROR("选择专业科目");
        }
        if (classes.getSubjectIds().split(",").length < 3) {
            return ResultUtil.ERROR("选择科目");
        }
        if (!DataUtil.isPositive(classes.getClassesType())) {
            return ResultUtil.ERROR("选择班级类型");
        }
        if (classes.getClassesType() == 1 && !DataUtil.idIsNotNull(classes.getCourseId())) {
            return ResultUtil.ERROR("选择班级课程");
        }
        if (StringUtils.isEmpty(classes.getImageJson())) {
            return ResultUtil.ERROR("上传班级图标");
        }
        if (StringUtils.lengthOutOfRange(classes.getSummary(), 1, 255)) {
            return ResultUtil.ERROR("班级简介1~255个字符");
        }
        if (StringUtils.isEmpty(classes.getHeadmasterIds())) {
            return ResultUtil.ERROR("选择班主任");
        }
        return null;
    }
}
